package com.shop.zzh.component.jwt;

import cn.hutool.json.JSONUtil;
import com.shop.zzh.dto.ResultCode;
import com.shop.zzh.dto.ResultJson;
import com.shop.zzh.result.ResultForm;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @program: zzh
 * @description: 当未登录或者token失效访问接口时，自定义的返回结果
 * @author: zhuzh
 * @create: 2019-12-16 22:32
 **/

public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
	@Override
	public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
		//验证为未登陆状态会进入此方法，认证错误
		System.out.println("认证失败：" + e.getMessage());
		httpServletResponse.setStatus(200);
		httpServletResponse.setCharacterEncoding("UTF-8");
		httpServletResponse.setContentType("application/json; charset=utf-8");
		PrintWriter printWriter = httpServletResponse.getWriter();
		String body = ResultJson.failure(ResultCode.UNAUTHORIZED,e.getMessage()).toString();
		printWriter.write(body);
		printWriter.flush();
//		//重定向到登录页面
//		PrintWriter out = httpServletResponse.getWriter();
//		String login = "/zzh/login/toLoginPage.html";
//		out.println("<html>");
//		out.println("<script>");
//		out.println("top.location.href='" + login + "'");
//		out.println("</script>");
//		out.println("</html>");
//		out.flush();
//		out.close();
//		return;
	}
}
